<?php

namespace app\common\entity;

use think\Exception;

class ResponseData extends Entity
{
    protected static $instance;

    protected $code = SUCCESS;
    protected $msg = '成功';
    protected $data = [];
    protected $ext = [];

    public static function success($data, $ext = [], $code = SUCCESS)
    {
        if (empty(self::$instance)) {
            self::$instance = new static();
        }
        self::$instance->data = $data;
        self::$instance->ext = $ext;
        self::$instance->code = $code;
        if (request()->header('accept') == 'application/json') {
            return self::$instance->__toArray();
        }else{
            return json_encode(self::$instance->__toArray());
        }
    }

    public static function error($msg, $code = 0)
    {
        if (empty(self::$instance)) {
            self::$instance = new static();
        }
        self::$instance->code = $code;
        self::$instance->msg = $msg;

        return self::$instance->__toArray();
    }

    public static function exception(Exception $exception)
    {
        if (empty(self::$instance)) {
            self::$instance = new static();
        }
         trace($exception->getFile().'['.$exception->getLine().']'.$exception->getMessage(), 'error');
        self::$instance->code = $exception->getCode();
        self::$instance->msg = $exception->getMessage();

        return self::$instance->__toArray();
    }
}